import { BrowserWindow } from 'electron'
import { MQTTClient, MQTTConfig, AppInfoResponse, WarnStatusResponse, DEFAULT_MQTT_CONFIG } from './mqttClient'

// MQTT服务类
export class MQTTService {
  private mqttClient: MQTTClient | null = null
  private appInfo: AppInfoResponse | null = null
  private warnStatus: WarnStatusResponse | null = null
  private isInitialized = false
  private initializationPromise: Promise<void> | null = null
  private mainWindow: BrowserWindow | null = null

  constructor() {
    this.resetState()
  }

  // 设置主窗口引用
  setMainWindow(window: BrowserWindow): void {
    this.mainWindow = window
  }

  // 重置服务状态
  private resetState(): void {
    this.mqttClient = null
    this.appInfo = null
    this.warnStatus = null
    this.isInitialized = false
    this.initializationPromise = null
  }

  // 初始化MQTT连接
  async initialize(
    brokerUrl: string,
    username: string,
    password: string,
    clientId: string
  ): Promise<void> {
    if (this.initializationPromise) {
      return this.initializationPromise
    }

    if (this.isInitialized && this.mqttClient) {
      return Promise.resolve()
    }

    // 创建自定义配置
    const config: MQTTConfig = {
      ...DEFAULT_MQTT_CONFIG,
      brokerUrl,
      username,
      password,
      clientId
    }

    this.initializationPromise = this.performInitialization(config)
    return this.initializationPromise
  }

  // 执行实际的初始化逻辑
  private async performInitialization(config: MQTTConfig): Promise<void> {
    try {
      this.resetState()

      this.mqttClient = new MQTTClient(config)
      await this.mqttClient.connect()
      
      // 订阅应用信息响应主题
      this.mqttClient.subscribe(config.topics.APP_INFO_RESPONSE, (message: AppInfoResponse) => {
        this.handleAppInfoResponse(message)
      })

      // 订阅警告状态响应主题
      this.mqttClient.subscribe(config.topics.WARN_STATUS_RESPONSE, (message: WarnStatusResponse) => {
        this.handleWarnStatusResponse(message)
      })

      // 请求应用信息
      this.requestAppInfo()
      
      this.isInitialized = true
      console.log('MQTT服务初始化成功')
    } catch (error) {
      console.error('MQTT服务初始化失败:', error)
      this.resetState()
      throw error
    } finally {
      this.initializationPromise = null
    }
  }

  // 处理应用信息响应
  private handleAppInfoResponse(response: AppInfoResponse): void {
    if (response.code === 1 && response.msg === 'ok') {
      this.appInfo = response
      console.log('收到应用信息:', response)
      
      // 通知渲染进程
      if (this.mainWindow) {
        this.mainWindow.webContents.send('mqtt-app-info-update', response)
      }
    } else {
      console.error('应用信息响应错误:', response)
    }
  }

  // 处理警告状态响应
  private handleWarnStatusResponse(response: WarnStatusResponse): void {
    if (response.code === 1 && response.msg === 'ok') {
      this.warnStatus = response
      console.log('收到警告状态:', response)
      
      // 通知渲染进程
      if (this.mainWindow) {
        this.mainWindow.webContents.send('mqtt-warn-status-update', response)
      }
    } else {
      console.error('警告状态响应错误:', response)
    }
  }

  // 请求应用信息
  requestAppInfo(): void {
    if (this.mqttClient) {
      const request = { request: 1 }
      this.mqttClient.publish(DEFAULT_MQTT_CONFIG.topics.APP_INFO_REQUEST, request)
    }
  }

  // 请求警告状态数据
  requestWarnStatus(): void {
    if (this.mqttClient) {
      this.mqttClient.requestWarnStatus()
    }
  }

  // 获取当前应用信息
  getAppInfo(): AppInfoResponse | null {
    return this.appInfo
  }

  // 获取当前警告状态
  getWarnStatus(): WarnStatusResponse | null {
    return this.warnStatus
  }

  // 获取连接状态
  getConnectionStatus(): boolean {
    return this.mqttClient ? this.mqttClient.getConnectionStatus() : false
  }

  // 获取初始化状态
  getInitializationStatus(): boolean {
    return this.isInitialized
  }

  // 检查服务是否可用
  isServiceAvailable(): boolean {
    return this.isInitialized && this.getConnectionStatus()
  }

  // 断开连接
  disconnect(): void {
    if (this.mqttClient) {
      this.mqttClient.disconnect()
      this.mqttClient = null
      this.isInitialized = false
      console.log('MQTT服务已断开连接')
    }
  }

  // 重新连接
  async reconnect(): Promise<void> {
    if (this.mqttClient) {
      try {
        await this.mqttClient.connect()
        console.log('MQTT服务重连成功')
      } catch (error) {
        console.error('MQTT服务重连失败:', error)
        throw error
      }
    }
  }

  // 获取服务状态
  getServiceStatus(): {
    isInitialized: boolean
    isConnected: boolean
    isAvailable: boolean
    reconnectAttempts?: number
  } {
    return {
      isInitialized: this.isInitialized,
      isConnected: this.getConnectionStatus(),
      isAvailable: this.isServiceAvailable(),
      reconnectAttempts: this.mqttClient?.getReconnectAttempts()
    }
  }
}
